package org.sam.swing.interpreter;

import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * 计算公式js版本实现
 * 
 * @author Administrator
 *
 */
public class NashornEnginee implements Enginee {

	/**
	 * 当前的计算公式引擎对象
	 */
	private static ScriptEngine engine;

	/**
	 * js里面用到的前缀对象
	 */
	public final static String preFix = "o";

	/**
	 * jsfile地址
	 * 是系统自定义函数集合
	 */
	public static String jsFile;

	/**
	 * 初始化引擎对象
	 */
	static {
		engine = new ScriptEngineManager().getEngineByName("nashorn");
		jsFile = "funs.js";
		try {

			FileReader fr = new FileReader(jsFile);
			engine.eval(fr);
			fr.close();
			
//			/*为文件注入全局变量*/
//	        Bindings bindings = engine.createBindings();  
//	        bindings.put("factor", 2);
//	        /*设置绑定参数的作用域*/
//	        engine.setBindings(bindings,ScriptContext.ENGINE_SCOPE);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * {@inheritDoc}
	 * @throws ScriptException 
	 */
	@Override
	public Object eval(String expression) throws Exception {
		return engine.eval(expression);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object callFun(String funName) throws Exception  {
		Invocable in = (Invocable) engine;
		return in.invokeFunction(funName);
	}

	/**
	 * {@inheritDoc}
	 * 载入js文件并执行
	 */
	@Override
	public void loadLib(String fileName) throws Exception  {
		try {

			FileReader fr = new FileReader(fileName);
			engine.eval(fr);
			fr.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
